import { NextResponse } from 'next/server';
import {  BurndownItem } from '@/types/Model';
import  db  from '@/lib/db';
import moment from 'moment';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const sprintId = searchParams.get('sprint_id');

  if (!sprintId) {
    return NextResponse.json({ error: 'Sprint ID is required' }, { status: 400 });
  }

  try {
    // 1. 获取 Sprint 数据
    const sprint = await db.sprint.findUnique({
      where: { id: sprintId },
      select: { start_date: true, end_date: true }
    });

    if (!sprint) {
      return NextResponse.json({ error: 'Sprint not found' }, { status: 404 });
    }
    const { start_date, end_date } = sprint;

    // 2. 从 backlog 获取总预估工时
    const backlogItems = await db.sprintUserStory.findMany({
      where: {
        sprint_id: sprintId
      },
      include: {
        user_story: {  // 联查 UserStory
          select: {
            estimate: true
          }
        }
      }
    });

    // 计算初始总工作量，处理可能的null值
    const initialTotalHours = backlogItems.reduce((sum: number, item:any) => {
      const estimate = item.user_story?.estimate ?? 0;
      return sum + (estimate * 8);
    }, 0);


    // 2. 获取当前 Sprint 的所有任务
   const tasks = await db.task.findMany({
    where: { 
      sprint_id: sprintId,
      create_time: {
        gte: `${start_date as string} 00:00:01`,
        lte: `${end_date as string} 23:59:59`
      }
    },
    select: { 
      end_time: true, 
      name: true,
      hours:true,
      status: true  // 新增：获取任务状态
    }
  });


  // 4. 计算每日剩余工作量
  const burndownData: BurndownItem[] = [];
  const dailyData: { [date: string]: number } = {};

  // 初始化日期范围
  let currentDate = moment(start_date).subtract(1, 'day');
  const endDate = moment(end_date);


  
  // 初始化每日完成量为0
  while (currentDate.isSameOrBefore(endDate)) {
    const dateStr = currentDate.format('YYYY-MM-DD');
    dailyData[dateStr] = 0;
    currentDate = currentDate.add(1, 'day');
  }

  // 计算每日完成工作量
  tasks.forEach(task => {
    // if (task.status === 'DONE') {
      const taskDate = moment(task.end_time).format('YYYY-MM-DD');
      dailyData[taskDate] += task.hours || 0;
      console.log(dailyData[taskDate])
    // }
  });

  // console.log('Initial total hours:', initialTotalHours);
  // console.log('Daily data:', dailyData);
  // console.log('Tasks:', tasks);

  // 5. 生成燃尽图数据
  let totalRemaining = initialTotalHours;
  const sortedDates = Object.keys(dailyData).sort();

  // 添加第一天（初始值）
  burndownData.push({
    date: sortedDates[0],
    remainingHours: totalRemaining
  });

  // 计算每日剩余工作量
  for (let i = 1; i < sortedDates.length; i++) {
    const currentDate = sortedDates[i];
    // 减去当天完成的工作量
    totalRemaining -= dailyData[currentDate];
    
    burndownData.push({
      date: currentDate,
      remainingHours: Math.max(0, totalRemaining)
    });
  }

    return NextResponse.json(burndownData);
  } catch (error) {
    console.error('Error calculating burndown data:', error);
    return NextResponse.json(
      { 
        error: 'Failed to calculate burndown data',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}
